import cv2
import numpy as np
import pytesseract
import re

# 配置Tesseract路径（根据实际安装路径修改）
pytesseract.pytesseract.tesseract_cmd = r'D:\tesseract\tesseract.exe'

def preprocess_image(img):
    """图像预处理：增强对比度"""
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    enhanced = clahe.apply(gray)
    _, thresh = cv2.threshold(enhanced, 120, 255, cv2.THRESH_BINARY_INV)
    return thresh

def find_main_display(img, target_width=809, target_height=480):
    """通过独立匹配宽高定位目标区域"""
    processed = preprocess_image(img)
    contours, _ = cv2.findContours(processed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    candidates = []
    for cnt in contours:
        (x, y, w, h) = cv2.minAreaRect(cnt)
        # 计算宽度和高度与目标的独立距离
        width_diff = abs(w - target_width)
        height_diff = abs(h - target_height)
        # 综合距离（可调整权重）
        total_diff = 0.5 * width_diff + 0.5 * height_diff
        candidates.append((x, y, w, h, total_diff))
    
    if not candidates:
        return None
    
    # 选择综合距离最小的候选区域
    main_roi = min(candidates, key=lambda c: c[4])
    return main_roi[:4]  # 返回(x, y, w, h)

def extract_values(img_path):
    img = cv2.imread(img_path)
    new_size = (1200, 800)
    img = cv2.resize(img, new_size)
    if img is None:
        return {"voltage": None, "resistance": None}
    
    # 定位主显示区域
    main_roi = find_main_display(img)
    if not main_roi:
        return {"voltage": None, "resistance": None}
    
    x, y, w, h = main_roi
    display_roi = img[y:y+h, x:x+w]
    
    cv2.imshow("haha", display_roi)
    cv2.waitKey(0)
    # # OCR识别优化
    # gray_roi = cv2.cvtColor(display_roi, cv2.COLOR_BGR2GRAY)
    # _, roi_thresh = cv2.threshold(gray_roi, 120, 255, cv2.THRESH_BINARY_INV)
    
    # # 使用严格的白名单和单位匹配
    # custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.mΩV'
    # text = pytesseract.image_to_string(roi_thresh, config=custom_config)
    
    # # 正则表达式匹配
    # voltage_match = re.search(r'(\d+\.?\d*)\s*V', text)
    # resistance_match = re.search(r'(\d+\.?\d*)\s*(mΩ|Ω)', text)
    
    # result = {}
    # if voltage_match:
    #     result['voltage'] = float(voltage_match.group(1))
    # if resistance_match:
    #     value = float(resistance_match.group(1))
    #     unit = resistance_match.group(2)
    #     result['resistance'] = value * (1e-3 if unit == 'mΩ' else 1)
    
    # return result

# 使用示例
if __name__ == "__main__":
    import os
    for file in os.listdir("images"):
        extract_values(f"./images/{file}")
    # print(f"电压: {result.get('voltage', 'N/A')}V, 内阻: {result.get('resistance', 'N/A')}mΩ")